<template>
  <transition name="el-zoom-in-center">
    <div class="jsbos-preview-main">
      <div class="jsbos-common-page-header">
        <el-page-header
          @back="goBack"
          :content="!dataForm.id ? '新建' : '编辑'"
        />
        <div class="options">
          <el-button
            :loading="btnLoading"
            type="primary"
            @click="dataFormSubmit()"
          >
            保 存</el-button
          >
          <el-button @click="goBack"> 取 消</el-button>
        </div>
      </div>
      <el-row
        :gutter="15"
        class="main"
        :style="{ margin: '0 auto', width: '1000px' }"
        style="padding-bottom: 100px"
      >
        <el-form
          ref="elForm"
          :model="dataForm"
          :rules="rules"
          size="small"
          label-width="100px"
          label-position="right"
        >
          <template v-if="!loading">
            <el-col :xs="24" :md="12" :lg="8" :xl="6">
              <el-form-item label="试卷目录" prop="categoryId">
                <tree-select
                  ref="categoryTreeSelectRef"
                  v-model="dataForm.categoryId"
                  :options="categoryIdOptions"
                  :props="categoryIdProps"
                  :isChangeFather="false"
                  :style="{ width: '100%' }"
                  placeholder="请选择"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="12" :lg="8" :xl="6">
              <el-form-item label="试卷名称" prop="fullName">
                <el-input
                  v-model="dataForm.fullName"
                  placeholder="请输入"
                  clearable
                  :style="{ width: '100%' }"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="试卷介绍" prop="intro">
                <el-input
                  v-model="dataForm.intro"
                  placeholder="请输入"
                  :maxlength="500"
                  :style="{ width: '100%' }"
                  true
                  type="textarea"
                  :autosize="{ minRows: 1, maxRows: 4 }"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label-width="0">
                <group-title content="固定试题" class="mb-20" />
                <div style="margin-bottom: 5px">
                  <el-button icon="el-icon-plus" @click="addQuestions()"
                    >添加试题
                  </el-button>
                  <el-button
                    icon="el-icon-setting"
                    @click="scoreSettingHandel()"
                    >分值设置
                  </el-button>
                </div>
                <el-table :data="dataForm.questions" size="mini" border>
                  <el-table-column
                    type="index"
                    width="50"
                    label="序号"
                    :align="'center'"
                  />
                  <!-- <el-table-column prop="paperId" label="试卷id">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.paperId"
                        placeholder="请输入"
                        clearable
                        :style="{ width: '100%' }"
                      >
                      </el-input>
                    </template>
                  </el-table-column> -->
                  <el-table-column prop="questionName" label="试题">
                  </el-table-column>
                  <el-table-column prop="questionTypeName" label="题型">
                  </el-table-column>
                  <el-table-column prop="score" label="分值设置">
                    <template slot-scope="scope">
                      <el-input-number
                        v-model="scope.row.score"
                        placeholder="数字文本"
                        :style="{ width: '100%' }"
                        :precision="1"
                        :step="0.1"
                        :min="0"
                        controls-position="right"
                        @change="sumTotalScore"
                      >
                      </el-input-number>
                    </template>
                  </el-table-column>
                  <el-table-column prop="missedScore" label="漏选给分">
                    <template slot-scope="scope">
                      <el-input-number
                        :disabled="
                          scope.row.questionType == 'multiple' ? false : true
                        "
                        v-model="scope.row.missedScore"
                        placeholder="数字文本"
                        :style="{ width: '100%' }"
                        :precision="1"
                        :step="0.1"
                        :min="0"
                        controls-position="right"
                      >
                      </el-input-number>
                    </template>
                  </el-table-column>
                  <el-table-column prop="scoreType" label="评分规则(填空题)">
                    <template slot-scope="scope">
                      <el-select
                        :disabled="
                          scope.row.questionType == 'blank' ? false : true
                        "
                        v-model="scope.row.scoreType"
                        placeholder="请选择"
                        :style="{ width: '100%' }"
                      >
                        <el-option
                          v-for="(item, index) in scoreTypeOptions"
                          :key="index"
                          :label="item.fullName"
                          :value="item.id"
                          :disabled="item.disabled"
                        ></el-option>
                      </el-select>
                    </template>
                  </el-table-column>
                  <!-- <el-table-column
                    prop="subQuestionScoreRule"
                    label="评分规则(案例题)"
                  >
                    <template slot-scope="scope">
                      <el-select
                        :disabled="
                          scope.row.questionType == 'cases' ? false : true
                        "
                        v-model="scope.row.subQuestionScoreRule"
                        placeholder="请选择"
                        :style="{ width: '100%' }"
                      >
                        <el-option
                          v-for="(item, index) in subQuestionScoreRuleOptions"
                          :key="index"
                          :label="item.fullName"
                          :value="item.id"
                          :disabled="item.disabled"
                        ></el-option>
                      </el-select>
                    </template>
                  </el-table-column> -->
                  <el-table-column label="操作" width="50">
                    <template slot-scope="scope">
                      <el-button
                        size="mini"
                        type="text"
                        class="jsbos-table-delBtn"
                        @click="delQuestions(scope.$index)"
                      >
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <div class="jsbos-common-title" style="margin-bottom: 20px">
                <h2>总分与及格线</h2>
              </div>
            </el-col>
            <el-col :span="4">
              <el-form-item label="总分：" prop="myScore">
                <template>
                  {{ dataForm.myScore }}
                </template>
              </el-form-item>
            </el-col>
            <el-col :span="20">
              <el-form-item label="及格线(%)：" prop="passLine">
                <el-input-number
                  v-model="dataForm.passLine"
                  placeholder="数字文本"
                  :max="100"
                  :min="0"
                  :step="1"
                  controls-position="right"
                  @change="sumPassScore"
                >
                </el-input-number>
                <span style="color: rgb(140, 140, 140); margin-left: 30px"
                  >及格分（{{ dataForm.passScore }}） = 总分（{{
                    dataForm.myScore
                  }}） * 及格线（{{ dataForm.passLine }}%）</span
                >
              </el-form-item>
            </el-col>
          </template>
        </el-form>
      </el-row>
      <QuestionDialog
        ref="questionRef"
        v-if="questionVisible"
        :questionIds="dataForm.questions"
        @table-change="selectQuestionChange"
      >
      </QuestionDialog>
      <ScoreSettingDialog
        ref="scoreSettingRef"
        v-if="scoreSettingVisible"
        @close="scoreSettingDialogClose"
        @submit="batchScoreSetting"
      >
      </ScoreSettingDialog>
    </div>
  </transition>
</template>
<script>
import { getInfo, Update, Create } from "@/views/exam/api/paper";
import QuestionDialog from "@/views/exam/paper/questionDialog.vue";
import ScoreSettingDialog from "@/views/exam/paper/scoreSettingDialog.vue";

export default {
  components: { QuestionDialog, ScoreSettingDialog },
  props: {
    categoryIdOptions: {
      type: Array,
      default: [],
    },
    categoryIdProps: {
      type: Object,
      default: {
        children: "children",
        label: "fullName",
        value: "id",
      },
    },
  },
  data() {
    return {
      visible: false,
      questionVisible: false,
      scoreSettingVisible: false,
      loading: false,
      btnLoading: false,
      paperType: "1", // 1-固定版本 2-随机版本
      dataForm: {
        categoryId: "",
        enCode: "",
        fullName: "",
        intro: "",

        paperrandomVersion: "2",
        openDifficultyGrade: 0,
        folders: "",
        passLine: 60,
        myScore: 0,
        passScore: 0,
        description: "",
        enabledMark: 1,
        rules: [],
        questions: [],
      },
      rules: {
        categoryId: [
          {
            required: true,
            message: "请选择",
            trigger: "change",
          },
        ],
        enCode: [
          {
            required: true,
            message: "请输入",
            trigger: "blur",
          },
        ],
        fullName: [
          {
            required: true,
            message: "请输入",
            trigger: "blur",
          },
        ],
        passLine: [
          {
            required: true,
            message: "请输入",
            trigger: "blur",
          },
        ],
      },

      questionTypeOptions: [],
      difficultyGradeIdOptions: [],
      scoreTypeOptions: [
        { fullName: "空", id: "1" },
        { fullName: "题", id: "2" },
      ],
      subQuestionScoreRuleOptions: [
        { fullName: "整题", id: "1" },
        { fullName: "每小题", id: "2" },
      ],
    };
  },
  computed: {},
  watch: {},
  created() {
    this.getquestionTypeOptions();
  },
  mounted() {},
  methods: {
    temsexampaperquestionExist() {
      let isOk = true;
      for (let i = 0; i < this.dataForm.questions.length; i++) {
        const e = this.dataForm.questions[i];
      }
      return isOk;
    },
    getquestionTypeOptions() {
      this.$store
        .dispatch("base/getDictionaryData", {
          encode: "questionType",
        })
        .then((res) => {
          this.questionTypeOptions = res;
        });
    },
    goBack() {
      this.$emit("refresh", this.paperType);
    },
    clearData(data) {
      for (let key in data) {
        if (data[key] instanceof Array) {
          data[key] = [];
        } else if (data[key] instanceof Object) {
          this.clearData(data[key]);
        } else {
          data[key] = "";
        }
      }
    },
    init(id) {
      this.dataForm.id = id || 0;
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["elForm"].resetFields();
        if (this.dataForm.id) {
          this.loading = true;
          getInfo(this.dataForm.id).then((res) => {
            this.dataInfo(res.data);
            this.loading = false;
          });
        } else {
          this.clearData(this.dataForm);
          this.dataForm.passLine = 60;
        }
      });
      this.$store.commit("generator/UPDATE_RELATION_DATA", {});
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["elForm"].validate((valid) => {
        if (valid) {
          if (!this.temsexampaperquestionExist()) return;
          var _data = this.dataList();
          this.btnLoading = true;
          const formMethod = this.dataForm.id ? Update : Create;
          formMethod(_data)
            .then((res) => {
              this.$message({
                message: res.msg,
                type: "success",
                duration: 1000,
                onClose: () => {
                  this.visible = false;
                  this.btnLoading = false;
                  this.$emit("refresh", true);
                },
              });
            })
            .catch(() => {
              this.btnLoading = false;
            });
        }
      });
    },
    // 添加试题 弹框
    addQuestions() {
      this.questionVisible = true;
      this.$nextTick(() => {
        this.$refs.questionRef.initData();
      });
    },
    // 选中试题 change事件
    selectQuestionChange(multipleSelection) {
      if (multipleSelection) {
        let _paperQuestionList = this.dataForm.questions;
        multipleSelection.forEach((item) => {
          let _question = {
            paperId: undefined,
            questionId: item.id,
            questionName: item.title,
            questionType: item.questionType,
            questionTypeName: item.questionTypeName,
            score: 1,
            missedScore: 0,
            scoreType: "2", // 1:空，2题。
            subQuestionScoreRule: "1", // 1:整题，2：每小题
          };
          // 判断是否已存在，并去重
          let _isExist = true;
          _paperQuestionList.forEach((_item) => {
            if (_item.questionId == item.id) {
              _isExist = false;
            }
          });
          if (_isExist) {
            _paperQuestionList.push(_question);
          }
        });
        this.dataForm.questions = _paperQuestionList;
      } else {
        this.dataForm.questions = [];
      }
      this.questionVisible = false;
      this.sumTotalScore();
    },
    // 批量设置分值 弹框
    scoreSettingHandel() {
      this.scoreSettingVisible = true;
      this.$nextTick(() => {
        this.$refs.scoreSettingRef.init(this.dataForm.questions);
      });
    },
    scoreSettingDialogClose() {
      this.scoreSettingVisible = false;
    },
    batchScoreSetting(scoreData) {
      let _data = scoreData[0];
      this.dataForm.questions.forEach((el, index, arr) => {
        if (el.questionType == "selectTi") _data = scoreData[0];
        if (el.questionType == "multiple") _data = scoreData[1];
        if (el.questionType == "determine") _data = scoreData[2];
        if (el.questionType == "blank") _data = scoreData[3];
        if (el.questionType == "answers") _data = scoreData[4];
        if (el.questionType == "cases") _data = scoreData[5];

        el.score = _data.score;
        el.scoreType = _data.scoreType;
        el.missedScore = _data.missedScore;
      });
      this.sumTotalScore();
    },
    // 批量设置分值 change事件
    scoreSettingChange() {
      this.scoreSettingVisible = false;
    },
    //删除试题
    delQuestions(index) {
      this.dataForm.questions.splice(index, 1);
      this.sumTotalScore();
    },
    // 计算 总分
    sumTotalScore() {
      let _totalScore = 0;
      this.dataForm.questions.forEach((item) => {
        item.score = item.score ? item.score : 0;
        _totalScore += item.score;
      });
      this.dataForm.myScore = _totalScore;
      this.sumPassScore();
    },
    // 计算 及格线
    sumPassScore() {
      let _passLine = this.dataForm.passLine;
      this.dataForm.passLine = _passLine ? _passLine : 0;
      _passLine = new Number(this.dataForm.passLine);
      let _totalScore = this.dataForm.myScore;
      this.dataForm.myScore = _totalScore ? _totalScore : 0;
      _totalScore = new Number(this.dataForm.myScore);
      this.dataForm.passScore = Math.round((_passLine * _totalScore) / 100);
      this.$forceUpdate();
    },

    dataList() {
      var _data = JSON.parse(JSON.stringify(this.dataForm));
      _data.openDifficultyGrade = parseInt(_data.openDifficultyGrade);
      _data.enabledMark = parseInt(_data.enabledMark);
      _data.deleteMark = parseInt(_data.deleteMark);
      for (let i = 0; i < _data.questions.length; i++) {
        var _list = _data.questions[i];
      }
      _data.paperType = this.paperType;
      return _data;
    },
    dataInfo(dataAll) {
      let _dataAll = dataAll;
      _dataAll.openDifficultyGrade = parseInt(_dataAll.openDifficultyGrade);
      _dataAll.enabledMark = parseInt(_dataAll.enabledMark);
      _dataAll.deleteMark = parseInt(_dataAll.deleteMark);
      for (let i = 0; i < _dataAll.questions.length; i++) {
        var _list = _dataAll.questions[i];
      }
      this.dataForm = _dataAll;
      this.sumTotalScore();
    },
  },
};
</script>
